package com.great.start;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import com.xiaoleilu.hutool.http.HttpUtil;
import com.xiaoleilu.hutool.json.JSONArray;
import com.xiaoleilu.hutool.json.JSONObject;
import com.xiaoleilu.hutool.json.JSONUtil;

/**
 * 网易云音乐Api
 * @author ShouZi
 *秋江冷，月清愁，芦花白头。寥阔江天数点星，远笛声幽。拈叶细看，枫叶丹红露湿透。
 */
public class MusicApi {
	
	private static final String ApiUrl  = GetProperties.getName("ApiUrl");
	
	private static final String playlist_detail = "/playlist/detail";
	
	private static final String music_url = "/music/url";
	
	/**
	 * 获取歌单详情
	 * @param MusicId
	 * @return
	 * @throws IOException
	 */
	public static List getPlaylist_detail(String MusicId) throws IOException{
		
		Elements ements = Jsoup.connect("http://music.163.com/playlist?id="+MusicId)
		        .header("Referer", "http://music.163.com/")
		        .header("Host", "music.163.com").get().select("ul[class=f-hide] a");
				List ids = new ArrayList(); 
				
				for (Element element : ements) {
					String a = element.toString();
					String songId = a.substring(a.indexOf("d")+2,a.indexOf(">") -1);
					ids.add(songId);
				}
				Util.print_sys("获取歌单内所有歌曲: "+ids.toString());
		return ids;
	}
	
	
	/**
	 * 获取音乐 url
	 * @param ids
	 * @return
	 */
	public static List getMusic_url(List ids){
		String rids = ids.toString().replaceAll("[", "");
		rids = rids.replaceAll("]", "");
		
		System.out.println(rids);
		HashMap<String, Object> paramMap = new HashMap<>();
		paramMap.put("id", rids);
		String result = HttpUtil.get(ApiUrl+music_url, paramMap);
		
		JSONObject songJson = JSONUtil.parseObj(result);
		JSONArray data = songJson.getJSONArray("data");
		
		List dwUrl = new ArrayList();
		for (int i = 0; i < data.size(); i++) {
			JSONObject dataObj = data.getJSONObject(i);
			String url = dataObj.getStr("url");
			dwUrl.add(url);
		}
		return dwUrl;
	}
	
}
